package com.siashan.toolkit.validation.validator;


import com.siashan.toolkit.core.enums.IBaseEnum;
import com.siashan.toolkit.validation.EnumValue4Enum;


import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.Serializable;

/**
 * 枚举之校验
 *
 * @author siashan
 * @since 2021/7/9 1:41 上午
 */
public class EnumValue4EnumValidator implements ConstraintValidator<EnumValue4Enum, Object> {

    private Class<? extends IBaseEnum> anEnum;

    /**
     * 是否允许空值
     */
    private boolean enableNull = false;

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        if (enableNull){
            if (null == o){
                return true;
            }
        }
        IBaseEnum anEnum1 = getEnum((Serializable) o);

        return null != anEnum1;
    }

    /**
     * 根据code得到对应的枚举值，如果不存在则返回默认值
     *
     * @param code         枚举的code值
     * @return 枚举
     * @since V1.0.1
     */
    private  IBaseEnum getEnum(Serializable code) {
        for (IBaseEnum enumObj : anEnum.getEnumConstants()) {
            if (code.equals(enumObj.getCode())) {
                return enumObj;
            }
        }
        return null;
    }


    @Override
    public void initialize(EnumValue4Enum constraintAnnotation) {
        anEnum = constraintAnnotation.enumValues();
        enableNull = constraintAnnotation.enableNull();
    }
}
